package com.lk.oauth2.server.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * @description: Token配置类
 * @author: Li Kang
 * @create: 2020-08-30 16:23
 */
@Configuration
public class TokenConfig {

  /// 使用redis存token
  // @Autowired private RedisConnectionFactory redisConnectionFactory;

  @ConfigurationProperties(prefix = "spring.datasource")
  @Bean
  public DataSource dataSource() {
    return new DruidDataSource();
  }

  public static final String SIGNING_KEY = "lk-key";

  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    ///    // 对称加密进行签名令牌，资源服务器也要采用此密钥进行解密，来校验令牌合法性
    //    converter.setSigningKey(SIGNING_KEY);

    // 读取oauth2.jsk 文件中的私钥，第二个参数口令 oauth2,私钥进行签名
    KeyStoreKeyFactory keyFactory =
        new KeyStoreKeyFactory(new ClassPathResource("oauth2.jks"), "oauth2".toCharArray());
    // 别名 oauth2
    converter.setKeyPair(keyFactory.getKeyPair("oauth2"));
    return converter;
  }

  @Bean
  public TokenStore tokenStore() {
    // 通过redis管理token
    // return new RedisTokenStore(redisConnectionFactory);

    // 通过jdbc管理token
    // return new JdbcTokenStore(dataSource());

    // 通过JWT管理token:这token包含了用户的信息
    return new JwtTokenStore(jwtAccessTokenConverter());
  }
}
